package com.example.demo;

import java.util.*;

import org.springframework.data.domain.Page;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

// 可以给Service起名，其他地方通过@Resource(name="userServiceJdbcTemplateImpl")或者@Qualifier("userServiceJdbcTemplateImpl")注入
@Service("userServiceJdbcTemplateImpl")
public class UserServiceImpl implements UserService {

    private JdbcTemplate jdbcTemplate;

    UserServiceImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int create(String name, Integer age, String email) {
        return jdbcTemplate.update("insert into USER(NAME, AGE, EMAIL) values(?, ?, ?)", name, age, email);
    }

    @Override
    public List<User> getByName(String name) {
        List<User> users = jdbcTemplate.query("select NAME, AGE, EMAIL from USER where NAME = ?", (resultSet, i) -> {
            User user = new User();
            user.setName(resultSet.getString("NAME"));
            user.setAge(resultSet.getInt("AGE"));
            return user;
        }, name);
        return users;
    }

    @Override
    public int deleteByName(String name) {
        return jdbcTemplate.update("delete from USER where NAME = ?", name);
    }

    @Override
    public int getAllUserCount() {
        return jdbcTemplate.queryForObject("select count(1) from USER", Integer.class);
    }

    @Override
    public List<User> getAllUsers() {
        List<User> users = jdbcTemplate.query("select * from USER", (resultSet, i) -> {
            User user = new User();
            user.setId(resultSet.getLong("ID"));
            user.setName(resultSet.getString("NAME"));
            user.setAge(resultSet.getInt("AGE"));
            user.setEmail(resultSet.getString("EMAIL"));
            return user;
        });
        return users;
    }

    @Override
    public List<User> getPageAllUsers(int page, int size) {
        List<User> users = new ArrayList<>();
        return users;
    }

    @Override
    public Page<User> getPageInfoAllUsers(int page, int size) {
        return null;
    }

    @Override
    public int deleteAllUsers() {
        return jdbcTemplate.update("delete from USER");
    }

}